package com.ayf.payment.game.api.channel.sky98;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.bean.BaseResData;
import com.ayf.payment.game.api.channel.BaseHandler;
import com.ayf.payment.game.api.dto.platform.SubstitutePayConfigDTO;
import com.ayf.payment.game.api.dto.platform.pay.WanXiangPayConfigParamVO;
import com.ayf.payment.game.api.exception.NullSetException;
import com.ayf.payment.game.api.httpclient.HttpUtils;
import com.ayf.payment.game.api.service.payment.faka.util.FaKaSignUtil;
import com.ayf.payment.game.api.service.platform.SubstitutePayConfigService;
import com.ayf.payment.game.api.type.MerchantPayOrderStatusEnum;
import com.ayf.payment.game.api.utils.BigDecimalUtil;
import com.ayf.payment.game.api.utils.RandomStrUtils;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;
import java.util.TreeMap;

@Component
public class Sky98PayHander implements BaseHandler {

	@Autowired
	private SubstitutePayConfigService substitutePayConfigService;

	@Override
	public JSONObject orderCreate(JSONObject inputParam) {
		JSONObject resJson = new JSONObject();
		String merchantOrderNo = inputParam.getString("merchant_order_no");
		resJson.put("merchantOrderNo", merchantOrderNo);
		resJson.put("status", MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus());

		String methodDesc = "捷付通代付下单";
		String traceId = inputParam.getString("traceId");
		Integer substitutePayConfigId = inputParam.getInteger("substitutePayConfigId");
		SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(substitutePayConfigId);
		WanXiangPayConfigParamVO wanXiangPayConfigParamVO = substitutePayConfigDTO.getWanXiangPayConfigParamVO();

		BaseResData baseResData = orderCreate(traceId, methodDesc, wanXiangPayConfigParamVO, inputParam);
		if (baseResData.isProcessing()) {
			resJson.put("status", MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus());
		}
		else {
			if (baseResData.isSuccess()) {
				JSONObject jsonResult = JSONObject.parseObject(baseResData.getData());
				String ret_code = jsonResult.getString("code");
				String message = jsonResult.getString("msg");
				if ("10000".equals(ret_code)) {
					String data = jsonResult.getString("data");
					if (StringUtils.isNotEmpty(data)) {
						JSONObject dataJson = JSONObject.parseObject(data);
						String channelOrderNo = dataJson.getString("serialNumber");
						resJson.put("channelOrderNo", channelOrderNo);
					}
					resJson.put("status", MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus());
				}
				else {
					resJson.put("status", MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
					resJson.put("failReason", message);
					LogPortal.error("{} {}失败，请求接口成功，接口返回错误码:{} 错误描述:{}", traceId, methodDesc, ret_code, message);
				}
			}
			else {
				resJson.put("status", MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
				resJson.put("failReason", baseResData.getRespMsg());
				LogPortal.error("{} {}失败，请求接口失败，返回错误码:{} 错误描述:{}", traceId, methodDesc, baseResData.getRespCode(), baseResData.getRespMsg());
			}
		}
		LogPortal.info("{} {} 响应报文[{}]", traceId, methodDesc, resJson.toJSONString());
		return resJson;
	}

	@Override
	public JSONObject orderQuery(JSONObject inputParam) {
		return null;
	}

	@Override
	public JSONObject balanceQuery(JSONObject inputParam) {
		JSONObject resJson = new JSONObject();
		resJson.put("status", "1");
		resJson.put("balance", "10000000.00");
		return resJson;
	}

	private BaseResData orderCreate(String traceId, String methodName, WanXiangPayConfigParamVO wanXiangPayConfigParamVO, JSONObject inputParam) {
		String merchantOrderNo = inputParam.getString("merchant_order_no");
		String AuthorizationURL = wanXiangPayConfigParamVO.getWebsite();
		String notifyUrl = wanXiangPayConfigParamVO.getNotifyurl();
		if (StringUtils.isEmpty(AuthorizationURL)) {
			LogPortal.error("{} {} 失败，通道代付地址不能为空，订单号:{}", traceId, methodName, merchantOrderNo);
			throw new NullSetException(traceId + "代付订单下单失败，请稍后重试！");
		}
		if (StringUtils.isEmpty(notifyUrl)) {
			LogPortal.error("{} {} 失败，代付异步通知地址不能为空，订单号:{}", traceId, methodName, merchantOrderNo);
			throw new NullSetException(traceId + "代付异步通知地址不能为空，请稍后重试！");
		}
		if (!AuthorizationURL.endsWith("/")) {
			AuthorizationURL = AuthorizationURL.concat("/");
		}
		if (!notifyUrl.endsWith("/")) {
			notifyUrl = notifyUrl.concat("/");
		}
		AuthorizationURL = AuthorizationURL.concat("api/v1/pay/repay");

		BigDecimal amount = inputParam.getBigDecimal("amount");
		String username = inputParam.getString("account_name");
		String bankName = inputParam.getString("bank_name");
		String bankno = inputParam.getString("account_no");
		String tradePwd = inputParam.getString("tradePwd");
		tradePwd = StringUtils.defaultIfEmpty(tradePwd, wanXiangPayConfigParamVO.getTradePwd());

		Map<String, String> reqParam = new TreeMap<>();
		reqParam.put("merchantId", wanXiangPayConfigParamVO.getParter());
		reqParam.put("requestId", merchantOrderNo);
		reqParam.put("amount", String.valueOf(BigDecimalUtil.yuanToFen(amount)));// 代付金额,单位分
		reqParam.put("bankName", username);
		reqParam.put("bankNumber", bankno);
		reqParam.put("bankType", bankName);
		reqParam.put("payKey", tradePwd);
		reqParam.put("notifyUrl", notifyUrl.concat("gameapip/v/sky98/pay/paynotify"));
		String sign = FaKaSignUtil.getSign(traceId, methodName, reqParam, wanXiangPayConfigParamVO.getKey());
		reqParam.put("code", sign);
		BaseResData result = HttpUtils.sendPostJson(traceId, methodName, AuthorizationURL, reqParam);
		return result;
	}

	private static void testOrderCreate() {
		String traceId = SnowFlakeUtils.getTraceId();
		JSONObject inputParam = new JSONObject();
		inputParam.put("merchant_order_no", "Y".concat(RandomStrUtils.createRandom(true, 8)));
		inputParam.put("amount", "1");
		inputParam.put("account_name", "张三");
		inputParam.put("bank_name", "招商银行");
		inputParam.put("account_no", "6225880132496432");
		WanXiangPayConfigParamVO wanXiangPayConfigParamVO = getTestWanXiangPayConfigParamVO();
		Sky98PayHander zhuoFuTongPayHandler = new Sky98PayHander();
		zhuoFuTongPayHandler.orderCreate(traceId, "捷付通代付下单", wanXiangPayConfigParamVO, inputParam);
	}

	/**
	 * 构造测试请求通道商户参数
	 *
	 * @return
	 */
	private static WanXiangPayConfigParamVO getTestWanXiangPayConfigParamVO() {
		WanXiangPayConfigParamVO wanXiangPayConfigParamVO = new WanXiangPayConfigParamVO();
		wanXiangPayConfigParamVO.setWebsite("http://tk.98tkpay.com");
		wanXiangPayConfigParamVO.setParter("sysAdmin");
		wanXiangPayConfigParamVO.setKey("721b36ad9af99f2d6c9b334446113a82");
		wanXiangPayConfigParamVO.setTradePwd("123456");
		wanXiangPayConfigParamVO.setNotifyurl("http://uatxy.111ao.cn");
		return wanXiangPayConfigParamVO;
	}

	public static void main(String[] args) {
		testOrderCreate();
	}

}
